import { useState } from 'react';
import './CodeBlock.css';

const CodeBlock = ({ language, code }) => {
  const [copied, setCopied] = useState(false);

  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(code);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (error) {
      console.error('复制失败:', error);
    }
  };

  const formatCode = (code) => {
    // 简单的SQL格式化
    if (language === 'sql') {
      return code
        .replace(/\bSELECT\b/gi, '\nSELECT')
        .replace(/\bFROM\b/gi, '\nFROM')
        .replace(/\bWHERE\b/gi, '\nWHERE')
        .replace(/\bORDER BY\b/gi, '\nORDER BY')
        .replace(/\bGROUP BY\b/gi, '\nGROUP BY')
        .replace(/\bHAVING\b/gi, '\nHAVING')
        .replace(/\bJOIN\b/gi, '\nJOIN')
        .replace(/\bLEFT JOIN\b/gi, '\nLEFT JOIN')
        .replace(/\bRIGHT JOIN\b/gi, '\nRIGHT JOIN')
        .replace(/\bINNER JOIN\b/gi, '\nINNER JOIN')
        .trim();
    }
    return code;
  };

  return (
    <div className="code-block-container">
      <div className="code-header">
        <span className="language-badge">
          {language?.toUpperCase() || 'CODE'}
        </span>
        <button 
          className="copy-button"
          onClick={handleCopy}
          title="复制代码"
        >
          {copied ? '✓ 已复制' : '📋 复制'}
        </button>
      </div>
      <div className="code-content">
        <pre>
          <code className={`language-${language}`}>
            {formatCode(code)}
          </code>
        </pre>
      </div>
    </div>
  );
};

export default CodeBlock;
